package com.v1.video.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.text.TextUtils;
import android.util.Xml;

import com.iss.httpclient.NormalHttpClient;
import com.iss.httpclient.core.HttpRequestException;
import com.iss.httpclient.core.HttpResponse;
import com.iss.httpclient.core.ParameterList;
import com.v1.video.exception.NetException;

public class WeatcherUtils {
    private static String[] formatCitykeys ={"市","地区","自治州","自治县","特别行政区","林区"};
    private static final String TAG = "WeatcherUtils";
    /**
     * 格式化城市名称为对应请求天气使用的城市
     * @param cityname
     * @return
     */
    public static String formatCityName(String cityname){
        if(TextUtils.isEmpty(cityname)){
            return "";
        }
        Logger.i(TAG, "格式化城市之前cityname="+cityname);
        int length = formatCitykeys.length;
        for(int i=0;i< length;i++ ){
            cityname = cityname.replaceAll(formatCitykeys[i], "");
        }
        Logger.i(TAG, "格式化城市之后cityname="+cityname);
        return cityname;
    }

    /**
     * 获取 天气预报
     * 
     * @param inputStream
     * @param city
     * @return
     * @throws IOException
     * @throws XmlPullParserException
     */
     public static String getCityWeatch(InputStream inputStream, String city) throws IOException,
            XmlPullParserException {
        // 将XML 中换成 城市名
        String soap = readSoapFile(inputStream, city);
        Logger.i(TAG, "城市名soap="+soap);
        byte[] data = soap.getBytes();
        // 提交Post请求
        URL url = new URL("http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setConnectTimeout(5000);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        OutputStream out = conn.getOutputStream();
        out.write(data);
        out.flush();
        out.close();
        if (conn.getResponseCode() == 200) {
            // 解析返回信息
            return parseResponseXML(conn.getInputStream());
        }

        return null;
    }

    /**
     * 解析 XML 文件
     * 
     * @param inputStream
     * @return
     * @throws XmlPullParserException
     * @throws IOException
     */
    private static String parseResponseXML(InputStream inputStream) throws XmlPullParserException,
            IOException {
        XmlPullParser xmlPullParser = Xml.newPullParser();
//        readInputStream(inputStream);
        xmlPullParser.setInput(inputStream, "UTF-8");
        int event = xmlPullParser.getEventType();
        List<String> lists = new ArrayList<String>();
        String str = null;
        while (event != XmlPullParser.END_DOCUMENT) {
            switch (event) {
                case XmlPullParser.START_TAG:
                    // 获取解析器当前指向的元素的名称

                    if ("string".equals(xmlPullParser.getName())) {
                        str = xmlPullParser.nextText();
                        lists.add(str);
                    }

                    break;
            }
            event = xmlPullParser.next();
        }
        if(lists.size()>7){
            String string = lists.get(7);
            String[] split = string.split(" ");
            return split[1];
//            lists.clear();
//            lists.add(split[1]);
        }else{
            if(lists.isEmpty()){
                return null;
            }else{
                return lists.get(0);
            }
        }
    }

    private static String readSoapFile(InputStream inputStream, String city) throws IOException {
        // 从流中获取文件信息
        byte[] data = readInputStream(inputStream);
        String soapxml = new String(data);
        // 占位符参数
        Map<String, String> params = new HashMap<String, String>();
        params.put("city", city);
        // 替换文件中占位符
        return replace(soapxml, params);
    }

    /**
     * 替换 文件中的 占位符
     * 
     * @param soapxml
     * @param params
     * @return
     */
    private static String replace(String soapxml, Map<String, String> params) {
        String result = soapxml;
        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String name = "\\$" + entry.getKey();
                Pattern pattern = Pattern.compile(name);
                Matcher matcher = pattern.matcher(result);
                if (matcher.find()) {
                    result = matcher.replaceAll(entry.getValue());
                }
            }
        }
        return result;
    }

    /**
     * 读取流信息
     * 
     * @param inputStream
     * @return
     * @throws IOException
     */
    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buf = new byte[1024];
        int len = -1;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((len = inputStream.read(buf)) != -1) {
            out.write(buf, 0, len);
            System.out.println(new String(buf));
        }
        out.close();
        inputStream.close();
        return out.toByteArray();
    }
    
    public String getCityWeather(String cityName,String url) throws Exception{
    	String code = "";
    	String weather = "";
//    	try{
    		String str = getJsonByGet(url, null);
    		Logger.i(TAG, "str之包含城市 代码字符串="+str);
    		if(str.contains("id=")){
	    		int index = str.indexOf("id=");
	    		int index1 = str.indexOf(";", index);
	    		code = str.substring(index+3, index1);
	    		weather = getWeatherFromCityCode(code);
	    		
	    		if(weather.equals("-1")){
	    			return "-1";
	    		}else{
	    			return weather;
	    		}
    		}else{
    			code = "-1";
    		}
    		Logger.i(TAG, "城市"+cityName+"代码="+code);
    		
//    	}catch(Exception e){
//    		e.printStackTrace();
//    		code = "-1";
//    	}
    	return code;
    }
    
    /**
     * 
     * @param cityCode 城市代码
     * @return
     * @throws NetException
     */
    private String getWeatherFromCityCode(String cityCode) throws NetException{
    	String weather = "";
//    	try{
    		
//    		String url = "http://www.weather.com.cn/data/cityinfo/101010100.html";
//    		String urlBefore = "http://www.weather.com.cn/data/cityinfo/";
    		String urlBefore = "http://m.weather.com.cn/atad/";
    		String urlAfter = ".html";
    		String url = urlBefore+cityCode+urlAfter;
    		String strWeather = getJsonByGet(url, null);
    		Logger.i(TAG, "根据城市代码获取的天气.json="+weather);
    		
    		if(strWeather.contains("\"weather1\":")){//"weather1":"晴"
    			int index = strWeather.indexOf("\"weather1\":");
    			int index1 = strWeather.indexOf("\",", index);
    			weather = strWeather.substring(index+12, index1);
    			Logger.i(TAG, "解析出来的天气weather="+weather);
    		}else{
    			return "-1";
    		}
//    		if(strWeather.contains("\"weather\":")){
//    			int index = strWeather.indexOf("\"weather\":");
//    			int index1 = strWeather.indexOf("\",", index);
//    			weather = strWeather.substring(index+11, index1);
//    			Logger.i(TAG, "解析出来的天气weather="+weather);
//    		}else{
//    			return "-1";
//    		}
//    	}catch(Exception e){
//    		e.printStackTrace();
//    		weather = "-1";
//    	}
    	return weather;
    }
    
    /**
     * 发送post请求，获取返回结果json字符串
     * @param path
     * @param params
     * @return
     * @throws NetException
     */
    private String getJsonByPost(String path, ParameterList params) throws NetException{
        NormalHttpClient mclient = new NormalHttpClient();
        HttpResponse response;
        try {
            response = mclient.post(path, params);
        } catch (HttpRequestException e) {
            e.printStackTrace();
            throw new NetException("网络请求异常，请检查网络");
        }
        String s = response.getBodyAsString();
        Logger.d("json",path+ "=" + s);
        return s;
    }
    
    /**
     * 发送get请求，获取返回结果json字符串
     * @param path
     * @param params
     * @return
     * @throws NetException
     */
    private String getJsonByGet(String path, ParameterList params) throws NetException{
        NormalHttpClient mclient = new NormalHttpClient();
        HttpResponse response;
        try {
            response = mclient.get(path, params);
        } catch (HttpRequestException e) {
            e.printStackTrace();
            throw new NetException("网络请求异常，请检查网络");
        }
        String s = response.getBodyAsString();
        Logger.d("json", path+"=" + s);
        return s;
    }
}
